package com.example.wujinapi.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.sql.DataSource;

/**
 * SpringBoot Security 配置
 * @email 3955296@qq.com
 * @date 2022/9/23/023 15:20
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    //请求页面授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http.headers().frameOptions().disable();  //解除iframe无法显示问题 Refused to display 'http://localhost:8080/' in a frame because it set 'X-Frame-Options' to 'deny'.
        http.csrf().disable(); //关闭csrf校验
        //首页所有人可以访问，功能页只有对应有权限的人才能访问
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/bg/login","/bg/login.html","/bg/pachong").permitAll() //这里需要斜杆
                .antMatchers("/bg/**").hasAuthority("user:admin"); //除了登录页，其它页面均需要管理员权限才可以登录查看
        //没有权限跳到登录页面
        http.formLogin().loginPage("/bg/login");
        http.logout().logoutSuccessUrl("/bg/login");
    }


    //如果启用了加密，那么系统就会用编码的格式去校验数据库密码，如果不一致，则会显示 用户或密码不正确
    /*@Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }*/


    //暴露方法，给后续使用
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //用户认证
    /*@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        // JDBC 模式
        *//*auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(new BCryptPasswordEncoder())
                .usersByUsernameQuery("SELECT username,password,enabled FROM users WHERE username=?")
                .authoritiesByUsernameQuery("SELECT username,authority FROM user_authorities where username=?");*//*

        auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(NoOpPasswordEncoder.getInstance())
                .withUser("admin").password("0192023a7bbd73250516f069df18b500").roles("user:admin");

    }*/
}
